﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TodoListApp.Commands;
using TodoListApp.Models;

namespace TodoListApp.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        //private string _todoContent = string.Empty;
        //public string TodoContent
        //{
        //    get => _todoContent;
        //    set
        //    {
        //        _todoContent = value;
        //    }
        //}

        private string _todoInput = string.Empty;
        private ObservableCollection<TodoItem> _todoItems = new();
        private readonly string _dataRepository = Path.Combine(
            Environment.CurrentDirectory,
            "todos.db"
        );
        
        public string TodoInput
        {
            get => _todoInput;
            set
            {
                _todoInput = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<TodoItem> TodoItems
        {
            get => _todoItems;
            set
            {
                _todoItems = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public ICommand AddCommand { get; }
        public ICommand DeleteCommand { get; }

        public MainViewModel()
        {
            //AddCommand = new RelayCommand(OnClick);
            AddCommand = new RelayCommand(AddTodoItem, CanAddTodoItem);
            DeleteCommand = new RelayCommand(DeleteSlectedItems, CanDeleteItems);
            InitializeDataRepository();
            LoadTodos();
        }

        private void OnClick()
        {
            //TodoContent = "按钮被点击了！（MVVM方式）";
            //MessageBox.Show(TodoContent, "提示");
        }

        private void AddTodoItem(object parameter)
        {
            TodoItems.Add(new TodoItem
            {
                TodoContent = TodoInput,
                IsSelected = false
            });
            AddTodo(TodoInput);
            TodoInput = string.Empty;
        }

        private bool CanAddTodoItem(object parameter)
        {
            return !string.IsNullOrWhiteSpace(TodoInput);
        }

        private void DeleteSlectedItems(object obj)
        {
            var selectedItems = TodoItems.Where(item =>  item.IsSelected).ToList();
            try
            {
                using var connection = new SqliteConnection($"Data Source={_dataRepository}");
                connection.Open();
                using var transaction = connection.BeginTransaction();
                string deleteQuery = "DELETE FROM todos WHERE todo_content = @todoContent";
                using var command = new SqliteCommand(deleteQuery, connection, transaction);
                foreach (var item in selectedItems)
                {
                    TodoItems.Remove(item);
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@todoContent", item.TodoContent);
                    command.ExecuteNonQuery();
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool CanDeleteItems(object obj)
        {
            return TodoItems.Any(item => item.IsSelected);
        }

        private void InitializeDataRepository()
        {
            try
            {
                var dir = Path.GetDirectoryName(_dataRepository) ?? throw new ArgumentNullException();
                Directory.CreateDirectory(dir);
                using var connection = new SqliteConnection($"Data Source={_dataRepository}");
                connection.Open();

                var createTableCommand = connection.CreateCommand();
                createTableCommand.CommandText = @"
                    CREATE TABLE IF NOT EXISTS todos (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    todo_content TEXT NOT NULL)
                ";
                createTableCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadTodos()
        {
            try
            {
                using var connection = new SqliteConnection($"Data Source={_dataRepository}");
                connection.Open();
                var selectCommand = connection.CreateCommand();
                selectCommand.CommandText = "SELECT todo_content FROM todos";
                using var reader = selectCommand.ExecuteReader();
                var items = new List<TodoItem>();
                while (reader.Read())
                {
                    items.Add(new TodoItem
                    {
                        TodoContent = reader.GetString(0),
                    });
                }

                TodoItems = new ObservableCollection<TodoItem>(items);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AddTodo(string todoInput)
        {
            try
            {
                using var connection = new SqliteConnection($"Data Source={_dataRepository}");
                connection.Open();
                var insertCommand = connection.CreateCommand();
                insertCommand.CommandText = @$"INSERT INTO todos (todo_content) VALUES ('{todoInput}')";
                insertCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
